package Cau1;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Calendar;
import java.util.Date;

public class UDPServer {

	DatagramSocket socket;
	public UDPServer(int port){
		try {
			socket = new DatagramSocket(port);
			System.out.println("Server is running...");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void run() throws IOException, ClassNotFoundException {
		FileOutputStream fos= new FileOutputStream("Example.txt",true); 
        PrintWriter pw= new PrintWriter(fos);
		byte[] buffer = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buffer, 1024);
		int i = 1;
		while (i < 4) {
			socket.receive(dp);
			NguonDien nd = ReadObjectFromPacket(dp);
			if (nd.getDienAp() == 0) 
				break;
			//displayObject(nd, i);
			Calendar dt = Calendar.getInstance();
			pw.printf("PC%d [%s] [%s]- [%fv, %fmA]", i, dp.getAddress(), dt.getTime(), nd.getDienAp(), nd.getDongDien());
			pw.println();
			i++;
		}
		System.out.println("Server closed.");
		pw.close();
	}
	private void displayObject(NguonDien e, int pc) {
		//System.out.printf("PC%d%f,%f\n",e.getDienAp(),e.getDongDien());
		
	}
	private NguonDien ReadObjectFromPacket(DatagramPacket dp) throws IOException, ClassNotFoundException {
		ByteArrayInputStream bi = new ByteArrayInputStream(dp.getData());
		ObjectInputStream os = new ObjectInputStream(bi);
		NguonDien nd = (NguonDien) os.readObject();
		return nd;
	}
	public static void main(String[] args) throws ClassNotFoundException, IOException {
		UDPServer server = new UDPServer(5000);
			server.run();
	}

}
